package com.star.spring.ratelimit.util;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

/**
 * 系统信息工具类
 *
 * @author star
 * @since 2025-01-24
 */
@Slf4j
@Component
public class SystemInfoUtil {

    private static final MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    private static final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

    /**
     * 获取服务器信息
     */
    public static String getServerInfo() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            String hostName = localHost.getHostName();
            String hostAddress = localHost.getHostAddress();

            return String.format("%s (%s) - %s %s",
                    hostName,
                    hostAddress,
                    osBean.getName(),
                    osBean.getVersion());
        } catch (Exception e) {
            log.warn("Failed to get server info", e);
            return "Unknown Server";
        }
    }

    /**
     * 获取当前内存使用情况（MB）
     */
    public static Long getMemoryUsed() {
        try {
            long usedMemory = memoryBean.getHeapMemoryUsage().getUsed();
            return usedMemory / (1024 * 1024); // 转换为MB
        } catch (Exception e) {
            log.warn("Failed to get memory usage", e);
            return 0L;
        }
    }

    /**
     * 获取CPU使用率（简化版本）
     */
    public static Double getCpuUsage() {
        try {
            // 这是一个简化的CPU使用率计算
            // 实际项目中可能需要使用更复杂的算法
            return osBean.getSystemLoadAverage();
        } catch (Exception e) {
            log.warn("Failed to get CPU usage", e);
            return 0.0;
        }
    }

    /**
     * 获取本机所有IP地址
     */
    public static String getAllLocalIPs() {
        try {
            StringBuilder ips = new StringBuilder();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (!networkInterface.isLoopback() && networkInterface.isUp()) {
                    Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        if (!address.isLoopbackAddress() && address.isSiteLocalAddress()) {
                            if (ips.length() > 0) {
                                ips.append(", ");
                            }
                            ips.append(address.getHostAddress());
                        }
                    }
                }
            }
            return ips.toString();
        } catch (Exception e) {
            log.warn("Failed to get local IPs", e);
            return "Unknown";
        }
    }

    /**
     * 获取JVM信息
     */
    public static String getJvmInfo() {
        try {
            Runtime runtime = Runtime.getRuntime();
            long maxMemory = runtime.maxMemory() / (1024 * 1024);
            long totalMemory = runtime.totalMemory() / (1024 * 1024);
            long freeMemory = runtime.freeMemory() / (1024 * 1024);

            return String.format("JVM: %s, Max: %dMB, Total: %dMB, Free: %dMB",
                    System.getProperty("java.version"),
                    maxMemory,
                    totalMemory,
                    freeMemory);
        } catch (Exception e) {
            log.warn("Failed to get JVM info", e);
            return "Unknown JVM";
        }
    }
}
